import time
import os
from django.db import models
from django.shortcuts import render, redirect
from Seller import models
from Seller import utils
from django.shortcuts import render

# Create your views here.
from Seller.utils import seller_decorator


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')

        password = utils.pwd_encrypt(password)

        models.Seller.objects.create(name=username, nickname=nickname, password=password)
        return redirect('/Seller/login/')
    return render(request, 'Seller/register.html')

def login(request):
    error_msg = ''
    if request.method == 'POST':
        username = request.POST.get('username')
        pwd = request.POST.get('password')
        pwd = utils.pwd_encrypt(pwd)
        ret = models.Seller.objects.filter(name=username, password=pwd)

        if ret:
            request.session['username'] = username
            seller_obj = ret.last()
            nickname = seller_obj.nickname
            request.session['nickname'] = nickname
            request.session['id'] = seller_obj.id
            request.session['time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            return redirect('/Seller/index/')
        else:
            error_msg = '账号或密码错误'

    return render(request, 'seller/login.html')

def logout(request):
    request.session.flush()
    return redirect('/Seller/login/')

@seller_decorator
def index(request):
    user_id = request.session.get("id")
    user_goods_num = models.Goods.objects.filter(seller_id=user_id).count()
    print('user_good_nums:', user_goods_num)
    # member_num = buyer_models.Buyer.objects.all().count()
    # print('member_nums:', member_num)
    # order_num = buyer_models.Order.objects.all().count()
    # print('order_nums:', order_num)

    print(locals())

    return render(request, 'seller/index.html', locals())

@seller_decorator
def type_add(request):
    if request.method == 'POST':
        type_name = request.POST.get("type_name")
        models.Type.objects.create(name=type_name)
        return redirect('/Seller/type_add/')
    return render(request, 'seller/type_add.html')

@seller_decorator
def type_list(request):
    type_obj_list = models.Type.objects.all()
    return render(request, 'seller/type_list.html', {'type_obj_list':type_obj_list})

@seller_decorator
def type_delete(request):
    id = request.GET.get('id')
    models.Type.objects.filter(id=id).delete()
    return redirect('/Seller/type_list/')

@seller_decorator
def type_change(request):
    if request.method == 'GET':
        id = request.GET.get('id')
        type_obj = models.Type.objects.get(id=id)
        return render(request, 'seller/type_change.html', {'type_obj': type_obj})
    else:
        id = request.POST.get('id')
        type_name = request.POST.get('type_name')
        models.Type.objects.filter(id=id).update(name=type_name)
        return redirect('/Seller/type_list/')

@seller_decorator
def goods_add(request):
    if request.method == 'POST':
        goods_num = request.POST.get("goods_num")
        goods_name = request.POST.get("goods_name")
        goods_oprice = request.POST.get("goods_oprice")
        goods_cprice = request.POST.get("goods_xprice")
        goods_kucun = request.POST.get("goods_kucun")
        goods_sales = request.POST.get("goods_sales")
        goods_description = request.POST.get("goods_description")
        goods_type_id = request.POST.get('goods_type')
        goods_content = request.POST.get('goods_content')
        userfiles = request.FILES.getlist('userfiles')

        goods_obj = models.Goods.objects.create(
            goods_num=goods_num,
            goods_name=goods_name,
            goods_oprice=goods_oprice,
            goods_cprice=goods_cprice,
            goods_kucun=goods_kucun,
            goods_sales=goods_sales,
            goods_description=goods_description,
            goods_details=goods_content,
            types=models.Type.objects.get(id=goods_type_id),
            seller_id=request.session.get('id')
        )

        for index, image_obj in enumerate(userfiles):
            name = image_obj.name.rsplit('.', 1)[1]
            path = 'Seller/static/seller/images/{}_{}.{}'.format(goods_name, index, name)
            with open(path, mode='wb') as f:
                for content in image_obj.chunks():
                    f.write(content)

            path1 ='seller/images/{}_{}.{}'.format(goods_name, index, name)

            obj_image = models.Image(
                img_address=path1,
                img_label=image_obj.name,
                goods=goods_obj
            )

            obj_image.save()

        return redirect('/Seller/goods_list/')
    else:
        type_obj_list = models.Type.objects.all()
        return render(request,'seller/goods_add.html', {'type_obj_list': type_obj_list})


@seller_decorator
def goods_list(request):
    seller_id = request.session.get('id')
    goods_obj_list = models.Goods.objects.filter(seller_id=seller_id)
    return render(request, 'seller/good_list.html', {'goods_obj_list':goods_obj_list})

@seller_decorator
def goods_delete(request):
    id = request.GET.get('id')
    goods_obj = models.Goods.objects.get(id=id)
    image_obj_list = goods_obj.image_set.all()
    for image_obj in image_obj_list:
        path = 'Seller/static/' + image_obj.img_address.name
        os.remove(path)

    image_obj_list.delete()

    goods_obj.delete()

    return redirect('/Seller/goods_list/')

def goods_change(request):
    if request.method == 'GET':
        id = request.GET.get('id')
        goods_obj = models.Goods.objects.get(id=id)
        type_obj_list = models.Type.objects.all()
        return render(request,'seller/good_change.html', {'goods_obj': goods_obj, 'type_obj_list': type_obj_list})
    else:
        goods_id = request.POST.get('id')
        goods_num = request.POST.get("goods_num")
        goods_name = request.POST.get("goods_name")
        goods_oprice = request.POST.get("goods_oprice")
        goods_xprice = request.POST.get("goods_xprice")  # 使用 goods_xprice 获取值
        goods_count = request.POST.get("goods_count")
        goods_sales = request.POST.get("goods_sales")
        goods_description = request.POST.get("goods_description")
        goods_type_id = request.POST.get("goods_type")
        goods_content = request.POST.get("goods_content")
        userfiles = request.FILES.getlist("userfiles")

        goods_obj = models.Goods.objects.get(id=goods_id)
        goods_obj.goods_num = goods_num
        goods_obj.goods_name = goods_name
        goods_obj.goods_oprice = goods_oprice
        goods_obj.goods_cprice = goods_xprice
        goods_obj.goods_kucun = goods_count
        goods_obj.goods_sales = goods_sales
        goods_obj.goods_description = goods_description
        goods_obj.goods_details = goods_content
        goods_obj.types = models.Type.objects.get(id=goods_type_id)
        goods_obj.save()

        image_obj_list = goods_obj.images_set.all()

        for image_obj in image_obj_list:
            path = 'Seller/static/' + image_obj.img_address.name
            os.remove(path)

        image_obj_list.delete()

        for index, image_obj in enumerate(userfiles):
            name = image_obj.name.replace('.', '1')[1]
            path = 'Seller/static/seller/images/{}_{}.{}'.format(goods_name, index, name)

            with open(path, mode='wb') as f:
                for content in image_obj.chunks():
                    f.write(content)

            obj_image = models.Image()
            path1 = 'seller/images/{}_{}.{}'.format(goods_name, index, name)
            obj_image.img_address = path1
            obj_image.img_label = image_obj.name
            obj_image.goods = goods_obj
            obj_image.save()

        return redirect('/Seller/goods_list/')